<template>
  <div class="series-list">
    <!-- 分集列表 -->
    <el-table
      :data="series"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column label="序号" width="80">
        <template #default="{ row }">
          {{ row.seqNo }}
        </template>
      </el-table-column>
      
      <el-table-column label="分集ID" prop="seriesId" min-width="200" />
      
      <el-table-column label="创建时间" min-width="180">
        <template #default="{ row }">
          {{ formatTime(row.createAt) }}
        </template>
      </el-table-column>
      
      <el-table-column label="更新时间" min-width="180">
        <template #default="{ row }">
          {{ formatTime(row.updateAt) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button color="#1c1d29" link size="small" @click="handleViewFile(row)" style="color: #3644E0;">
            <el-icon class="mr-1"><Document /></el-icon>查看文件
          </el-button>
          <el-button  link size="small" @click="handleDownloadFile(row)" style="color: #3644E0;">
            <el-icon class="mr-1"><Download /></el-icon>下载
          </el-button>
          <el-button type="warning" link size="small" @click="handleEditSeries(row)" style="color: #3644E0;">
            <el-icon class="mr-1"><Edit /></el-icon>编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 空状态 -->
    <el-empty
      v-if="!loading && series.length === 0"
      description="暂无分集数据"
      class="mt-8"
    />
    
    <!-- 文件内容查看弹窗 -->
    <el-dialog
      v-model="fileDialogVisible"
      title="文件内容"
      width="80%"
      destroy-on-close
    >
      <div v-if="fileContent" class="file-content">
        <div class="p-4 whitespace-pre-wrap bg-gray-50 rounded">
          {{ fileContent }}
        </div>
      </div>
      <div v-else class="text-center py-8">
        <el-icon class="text-gray-400 text-3xl mb-2"><Loading /></el-icon>
        <div class="text-gray-500">加载中...</div>
      </div>
    </el-dialog>
    
    <!-- 编辑分集弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑分集"
      width="70%"
      destroy-on-close
    >
      <template v-if="currentSeries">
        <el-form
          ref="seriesFormRef"
          :model="seriesForm"
          label-width="100px"
          label-position="top"
        >
          <el-form-item label="分集ID">
            <el-input v-model="seriesForm.seriesId" disabled />
          </el-form-item>
          
          <el-form-item label="序号" prop="seqNo">
            <el-input-number v-model="seriesForm.seqNo" :min="1" style="width: 100%" />
          </el-form-item>
          
          <el-form-item label="文件内容" prop="content">
            <el-input
              v-model="seriesForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入文件内容"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button color="#1c1d29" @click="handleSaveSeries" :loading="saveLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Download, Edit, Loading } from '@element-plus/icons-vue'
import { getDramaSeries } from '@/api/drama'

const props = defineProps({
  dramaId: {
    type: [Number, String],
    required: true
  }
})

const emit = defineEmits(['update'])

// 分集列表
const series = ref([])
const loading = ref(false)

// 查看文件弹窗
const fileDialogVisible = ref(false)
const fileContent = ref('')

// 编辑弹窗
const editDialogVisible = ref(false)
const currentSeries = ref(null)
const saveLoading = ref(false)
const seriesFormRef = ref(null)
const seriesForm = ref({
  seriesId: '',
  seqNo: 1,
  content: ''
})

// 获取分集列表
const fetchSeries = async () => {
  loading.value = true
  try {
    const res = await getDramaSeries(props.dramaId)
    series.value = res.data || []
  } catch (error) {
    console.error('获取分集列表失败:', error)
    ElMessage.error('获取分集列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 格式化时间戳
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(Number(timestamp))
  return date.toLocaleString()
}

// 查看文件
const handleViewFile = async (row) => {
  fileContent.value = ''
  fileDialogVisible.value = true
  
  try {
    // 模拟从URL加载文件内容
    // 实际项目中应该调用API获取文件内容
    setTimeout(() => {
      fileContent.value = `这是分集 ${row.seqNo} 的文件内容示例。\n\n该文件的ID是: ${row.seriesId}\n创建于: ${formatTime(row.createAt)}\n最后更新: ${formatTime(row.updateAt)}\n\n这里是具体的剧本内容...`
    }, 500)
  } catch (error) {
    console.error('获取文件内容失败:', error)
    ElMessage.error('获取文件内容失败，请重试')
    fileDialogVisible.value = false
  }
}

// 下载文件
const handleDownloadFile = (row) => {
  // 实际项目中应该从row.fileUrl下载文件
  ElMessage.success(`正在下载第${row.seqNo}集文件`)
  
  // 如果有文件URL，可以通过创建a标签并模拟点击来下载
  if (row.fileUrl) {
    const link = document.createElement('a')
    link.href = row.fileUrl
    link.download = `分集_${row.seqNo}.txt`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

// 编辑分集
const handleEditSeries = (row) => {
  currentSeries.value = row
  seriesForm.value = {
    seriesId: row.seriesId,
    seqNo: row.seqNo,
    content: '这是分集内容，实际项目中应该从API加载'
  }
  editDialogVisible.value = true
}

// 保存分集
const handleSaveSeries = async () => {
  saveLoading.value = true
  
  try {
    // 这里应该调用API保存分集
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 更新本地数据
    const index = series.value.findIndex(item => item.seriesId === currentSeries.value.seriesId)
    if (index !== -1) {
      series.value[index] = {
        ...currentSeries.value,
        seqNo: seriesForm.value.seqNo,
        updateAt: Date.now()
      }
    }
    
    ElMessage.success('保存成功')
    editDialogVisible.value = false
    emit('update')
  } catch (error) {
    console.error('保存分集失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saveLoading.value = false
  }
}

onMounted(() => {
  fetchSeries()
})
</script>

<style scoped>
.file-content {
  max-height: 60vh;
  overflow-y: auto;
}
</style> 